/**
 * 维护聊天中的“语音转文字”设置
 */
import { getLogger, Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

const logger = getLogger('services/features/voice-to-text')

export interface VoiceToTextSetting {
  enable: boolean
  secretId: string
  secretKey: string
  forwardToRobot: boolean
}

interface RespVoiceToTextSetting {
  Enable: boolean
  SecretId: string
  SecretKey: string
  IsAibot: boolean
}
function formatSetting(raw: RespVoiceToTextSetting | null): VoiceToTextSetting {
  if (!raw) return getSettingPlaceholder()
  return {
    enable: raw.Enable,
    secretId: raw.SecretId,
    secretKey: raw.SecretKey,
    forwardToRobot: raw.IsAibot,
  }
}

function getSettingPlaceholder(): VoiceToTextSetting {
  return {
    enable: false,
    secretId: '',
    secretKey: '',
    forwardToRobot: false,
  }
}

export class VoiceToText extends Service<Services> {
  async load() {
    const res = await API('/Config/GetSpeechConfig', { formatter: formatSetting })
    if (res.success) {
      return res.data
    } else {
      logger.warn('语音转文字设置加载失败', res.error)
      return getSettingPlaceholder()
    }
  }

  async update(setting: VoiceToTextSetting) {
    const resp = await API('/Config/SaveSpeechConfig', {
      data: {
        Enable: setting.enable,
        SecretId: setting.secretId,
        SecretKey: setting.secretKey,
        IsAibot: setting.forwardToRobot,
      },
    })
    if (!resp.success) logger.warn('语音转文字设置更新失败', resp.error)
    return resp
  }
}
